
package com.chuangjian.hire.qiniu.service.impl;

import com.chuangjian.hire.qiniu.config.QiNiuConfig;
import com.chuangjian.hire.qiniu.service.QiNiuTokenGetter;
import com.qiniu.common.Zone;
import com.qiniu.processing.OperationManager;
import com.qiniu.storage.Configuration;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 七牛云token生成
 */
@Component
public class QiNiuTokenGetterImpl implements QiNiuTokenGetter {

    @Autowired
    private QiNiuConfig qiNiuConfig;

    @Override
    public String getVideoSimpleToken(String bucketName, String priFix) {
        Auth auth = Auth.create(qiNiuConfig.getAccess_key(), qiNiuConfig.getSecret_key());
        StringMap policy = new StringMap();
        policy.put("saveKey", priFix + "$(etag)$(ext)");
        policy.put("returnBody", "{\"key\":\"$(key)\",\"hash\":\"$(etag)\",\"videoDuration\":$(avinfo.video.duration)");
        String upToken = auth.uploadToken(bucketName, null, 3600, policy);
        return upToken;
    }

    @Override
    public String getSimpleToken(String bucketName, String priFix) {
        Auth auth = Auth.create(qiNiuConfig.getAccess_key(), qiNiuConfig.getSecret_key());
        StringMap policy = new StringMap();
        policy.put("saveKey", priFix + "$(etag)$(ext)");
        String upToken = auth.uploadToken(bucketName, null, 3600, policy);
        return upToken;
    }

    @Override
    public String getReplaceToken(String bucketName, String originKey) {
        Auth auth = Auth.create(qiNiuConfig.getAccess_key(), qiNiuConfig.getSecret_key());
        StringMap policy = new StringMap();
        policy.put("saveKey", "$(etag)$(ext)");
        String upToken = auth.uploadToken(bucketName, originKey, 3600, policy, true);
        return upToken;
    }

    @Override
    public Auth getAuth() {
        return Auth.create(qiNiuConfig.getAccess_key(), qiNiuConfig.getSecret_key());
    }


    @Override
    public OperationManager getOperationManager() {
        Configuration cfg = new Configuration(Zone.zone0());
        Auth auth = Auth.create(qiNiuConfig.getAccess_key(), qiNiuConfig.getSecret_key());
        OperationManager operationManager = new OperationManager(auth, cfg);
        return operationManager;
    }
}
